﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MvvmEx.Dispatchers;
using MvvmEx.Enums;

namespace MvvmEx.Controls.Messager
{
    /// <summary>
    /// 按照步骤 1a 或 1b 操作，然后执行步骤 2 以在 XAML 文件中使用此自定义控件。
    ///
    /// 步骤 1a) 在当前项目中存在的 XAML 文件中使用该自定义控件。
    /// 将此 XmlNamespace 特性添加到要使用该特性的标记文件的根 
    /// 元素中: 
    ///
    ///     xmlns:MyNamespace="clr-namespace:MvvmEx.Controls.Messager"
    ///
    ///
    /// 步骤 1b) 在其他项目中存在的 XAML 文件中使用该自定义控件。
    /// 将此 XmlNamespace 特性添加到要使用该特性的标记文件的根 
    /// 元素中: 
    ///
    ///     xmlns:MyNamespace="clr-namespace:MvvmEx.Controls.Messager;assembly=MvvmEx.Controls.Messager"
    ///
    /// 您还需要添加一个从 XAML 文件所在的项目到此项目的项目引用，
    /// 并重新生成以避免编译错误: 
    ///
    ///     在解决方案资源管理器中右击目标项目，然后依次单击
    ///     “添加引用”->“项目”->[浏览查找并选择此项目]
    ///
    ///
    /// 步骤 2)
    /// 继续操作并在 XAML 文件中使用控件。
    ///
    ///     <MyNamespace:NotifyMessageBox/>
    ///
    /// </summary>
    public class NotifyMessageBox : Control
    {
        #region 字段

        private WrapperView _wrapperView;
        private NotifyMsg _notifyMsg;
        private Storyboard _startStoryboard;
        private Storyboard _endStoryboard;
        #endregion

        #region 委托

        public Action OkAction { get; set; }

        public Action DelAction { get; set; }
        #endregion

        static NotifyMessageBox()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(NotifyMessageBox), new FrameworkPropertyMetadata(typeof(NotifyMessageBox)));

            InitCommands();
        }

        public NotifyMessageBox(NotifyMsg notifyMsg)
        {
            _notifyMsg = notifyMsg;

            Title = notifyMsg.Title;
            Content = notifyMsg.Content;
            OkBtnText = notifyMsg.OkText;
            DelBtnText = notifyMsg.DelText;
            OkAction = notifyMsg.OkAction;
            DelAction = notifyMsg.DelAction;


            _wrapperView = new WrapperView { Opacity = 0, Border = { Child = this }, WindowStartupLocation = WindowStartupLocation.Manual, ShowInTaskbar = true };

            this.Loaded += NotifyMessageBox_Loaded;
        }

        private void NotifyMessageBox_Loaded(object sender, RoutedEventArgs e)
        {
            _wrapperView.Top = SystemParameters.FullPrimaryScreenHeight;
            _wrapperView.Left = SystemParameters.FullPrimaryScreenWidth - this.Width - 10;

            InitAnimation();
        }

        #region 标题

        public string Title
        {
            get { return (string)GetValue(TitleProperty); }
            set { SetValue(TitleProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Title.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty TitleProperty =
            DependencyProperty.Register("Title", typeof(string), typeof(NotifyMessageBox), new PropertyMetadata(string.Empty));

        #endregion

        #region 内容

        public string Content
        {
            get { return (string)GetValue(ContentProperty); }
            set { SetValue(ContentProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Content.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ContentProperty =
            DependencyProperty.Register("Content", typeof(string), typeof(NotifyMessageBox), new PropertyMetadata(string.Empty));

        #endregion

        #region 确定按钮内容

        public string OkBtnText
        {
            get { return (string)GetValue(OkBtnTextProperty); }
            set { SetValue(OkBtnTextProperty, value); }
        }

        // Using a DependencyProperty as the backing store for OkBtnText.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty OkBtnTextProperty =
            DependencyProperty.Register("OkBtnText", typeof(string), typeof(NotifyMessageBox), new PropertyMetadata(string.Empty));

        #endregion

        #region 删除按钮内容



        public string DelBtnText
        {
            get { return (string)GetValue(DelBtnTextProperty); }
            set { SetValue(DelBtnTextProperty, value); }
        }

        // Using a DependencyProperty as the backing store for DelBtnText.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty DelBtnTextProperty =
            DependencyProperty.Register("DelBtnText", typeof(string), typeof(NotifyMessageBox), new PropertyMetadata(string.Empty));



        #endregion

        #region 命令

        public static readonly RoutedCommand CloseCommand = new RoutedCommand("Close", typeof(NotifyMessageBox));

        public static readonly RoutedCommand OkCommand = new RoutedCommand("Ok", typeof(NotifyMessageBox));

        public static readonly RoutedCommand DelCommand = new RoutedCommand("Del", typeof(NotifyMessageBox));

        #endregion

        #region 初始化命令

        private static void InitCommands()
        {
            var excutedRoutedEventHandler = new ExecutedRoutedEventHandler(OnMessageBoxCommand);

            CommandManager.RegisterClassCommandBinding(typeof(NotifyMessageBox), new CommandBinding(NotifyMessageBox.CloseCommand, excutedRoutedEventHandler));
            CommandManager.RegisterClassCommandBinding(typeof(NotifyMessageBox), new CommandBinding(NotifyMessageBox.OkCommand, excutedRoutedEventHandler));
            CommandManager.RegisterClassCommandBinding(typeof(NotifyMessageBox), new CommandBinding(NotifyMessageBox.DelCommand, excutedRoutedEventHandler));
        }

        private static void OnMessageBoxCommand(object target, ExecutedRoutedEventArgs e)
        {
            if (e.Command == NotifyMessageBox.CloseCommand)
            {
                ((NotifyMessageBox)target).Close();
            }
            else if (e.Command == NotifyMessageBox.OkCommand)
            {
                ((NotifyMessageBox)target).Ok();
            }
            else if (e.Command == NotifyMessageBox.DelCommand)
            {
                ((NotifyMessageBox)target).Del();
            }
        }
        #endregion

        #region 初始化动画

        private void InitStartAnimation()
        {
            _startStoryboard = new Storyboard();

            var duration = new Duration(TimeSpan.FromMilliseconds(200));
            var yPosition = new DoubleAnimation(SystemParameters.FullPrimaryScreenHeight, SystemParameters.FullPrimaryScreenHeight - this.ActualHeight, duration);
            var touMing = new DoubleAnimation(0, 1, duration);

            _startStoryboard.Children.Add(yPosition);
            _startStoryboard.Children.Add(touMing);

            Storyboard.SetTarget(yPosition, _wrapperView);
            Storyboard.SetTarget(touMing, _wrapperView);
            Storyboard.SetTargetProperty(yPosition, new PropertyPath("Top"));
            Storyboard.SetTargetProperty(touMing, new PropertyPath("Opacity"));
        }

        private void InitEndAnimation()
        {
            _endStoryboard = new Storyboard();

            var duration = new Duration(TimeSpan.FromMilliseconds(200));
            var yPosition = new DoubleAnimation(SystemParameters.FullPrimaryScreenHeight - this.ActualHeight, SystemParameters.FullPrimaryScreenHeight, duration);
            var touMing = new DoubleAnimation(1, 0, duration);

            _endStoryboard.Children.Add(yPosition);
            _endStoryboard.Children.Add(touMing);

            Storyboard.SetTarget(yPosition, _wrapperView);
            Storyboard.SetTarget(touMing, _wrapperView);
            Storyboard.SetTargetProperty(yPosition, new PropertyPath("Top"));
            Storyboard.SetTargetProperty(touMing, new PropertyPath("Opacity"));

            _endStoryboard.Completed += _endStoryboard_Completed;
        }

        private void InitAnimation()
        {
            InitStartAnimation();

            InitEndAnimation();
        }

        #endregion

        #region 公有方法

        #region 显示

        public void Show()
        {
            _notifyMsg.Status = NotifyMsgStatusDefine.Showing;

            _wrapperView.Show();

            _startStoryboard.Begin();

            //5s后自动关闭
            Task.Factory.StartNew(() =>
            {
                Thread.Sleep(5000);

                DispatcherHelper.CheckBeginInvokeOnUI(Close);
            });
        }

        #endregion

        #region 删除

        public void Del()
        {
            DelAction?.Invoke();

            Close();
        }

        #endregion

        #region 关闭

        public void Close()
        {
            _notifyMsg.Status = NotifyMsgStatusDefine.Close;

            _endStoryboard.Begin();
        }

        private void _endStoryboard_Completed(object sender, System.EventArgs e)
        {
            _wrapperView.Close();
        }

        #endregion

        #region 确定

        public void Ok()
        {
            OkAction?.Invoke();

            Close();
        }

        #endregion

        #endregion
    }
}
